import pandas as pd
from django.http import response,JsonResponse
from django.http import StreamingHttpResponse


def readFile(request):
    filename = 'F:\\Sams\\static\\excelFile\\grade_detail.csv'
    df = pd.read_csv(filename,encoding='utf-8')
    temp = df[["高数","英语","C语言","Java","Python","数据结构"]]
    df["total"] = temp.sum(axis=1)
    df["avg"] = temp.mean(axis=1)
    df.to_csv("F:\\Sams\\static\\excelFile\\calulate.csv")
    return JsonResponse({})


def download(request):
    def file_iterator(file_name, chunk_size=512):#用于形成二进制数据
        with open(file_name,'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    the_file_name ="F:\\Sams\\static\\excelFile\\calulate.csv"#要下载的文件路径
    response =StreamingHttpResponse(file_iterator(the_file_name))#这里创建返回
    response['Content-Type'] = 'application/vnd.ms-excel'#注意格式
    response['Content-Disposition'] = 'attachment;filename="calulate.csv"'#注意filename 这个是下载后的名字
    return response